﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using permit.App_Code.DataAccess;
using permit.App_Code.Entity;
using System.Text;
using System.Data;


namespace permit.opPermit
{
    public partial class PermitInfo : System.Web.UI.Page
    {
        PermitAccess perAcc = new PermitAccess();
        AssginAccess assAcc = new AssginAccess();
        DepartmentAccess depAcc = new DepartmentAccess();
        string sturts;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UserTable user = (UserTable)Session["UserTable"];
                PermitTable permit = perAcc.GetPermit(Convert.ToInt32(Request.QueryString["per_ID"]));

                if (user == null)
                {
                    Response.Write("<script>alert('请先登录！')</script>");
                    Response.Redirect("~/default.aspx");
                }

                if (user.DEP_PRINT == 1 && permit.Per_Count > 0)
                {
                    Response.Redirect("~/main/Main.aspx?Sturt=Edit");
                }
                else
                {
                    if (user.DEP_PRINT == 1)
                    {
                        txtPerCode.Enabled = false;
                        btnAutoCode.Enabled = false;
                        rblDatetype.Enabled = false;
                        btnPrint.Enabled = false;
                        txtPerDate.Enabled = false;
                        txtEndDate.Enabled = false;
                        ddlOrgan.Enabled = false;
                        RequiredFieldValidator7.Enabled = false;
                    }
                    


                }

                DataSet ds = depAcc.GetDepartments();

                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (dr["dep_AreaCode"].ToString() == user.DEP_AREACODE && user.DEP_AREACODE != "620100")
                    {
                        if (Convert.ToInt32(dr["dep_Print"].ToString()) == 1)
                        {
                            ddlOrgan.Items.Add(new ListItem("兰州市食品药品监督管理局", "620100"));
                        }
                        ddlOrgan.Items.Add(new ListItem(dr["dep_Name"].ToString(), dr["dep_AreaCode"].ToString()));
                        break;
                    }
                    if (user.DEP_AREACODE == "620100")
                    {
                        if (Convert.ToInt32(dr["dep_Print"]) == 0)
                        {
                            ddlOrgan.Items.Add(new ListItem(dr["dep_Name"].ToString(), dr["dep_AreaCode"].ToString()));
                        }
                    }

                }

                btnDelete.Attributes.Add("onclick", "javascript:return(confirm('是否要删除该条记录！'))");
                sturts = Request.QueryString["Sturt"];

                if (sturts == "Edit")
                {

                    //PermitTable permit = perAcc.GetPermit(Convert.ToInt32(Request.QueryString["per_ID"]));
                    if (permit.Per_PermitCode != null)
                    {
                        btnAutoCode.Enabled = false;
                        //txtPerCode.ReadOnly = true;
                        hdCode.Value = permit.Per_PermitCode;
                        ddlOrgan.SelectedValue = permit.Per_Organ;
                    }
                    else
                    {
                        btnPrint.Enabled = false;
                    }
                    txtDepartment.Text = permit.Per_Department;
                    txtRep.Text = permit.Per_Representative.Split('（')[0];
                    rblRep.SelectedValue = permit.Per_Representative.Split('（')[1].Split('）')[0];
                    rblDatetype.SelectedValue = permit.Per_PerType;

                    if (rblDatetype.SelectedIndex != 0)
                    {
                        txtEndDate.Enabled = true;
                        lblEndDate.Enabled = true;

                    }

                    txtAddress.Text = permit.Per_Address;
                    ddlType.SelectedValue = permit.Per_Type;
                    txtPerCode.Text = permit.Per_PermitCode;

                    if (permit.PermitDate == DateTime.MinValue)
                    {
                        txtPerDate.Text = "";
                    }
                    else
                    {
                        if (permit.PermitDate.ToShortDateString().Split('-')[2].Length > 1)
                        {
                            txtPerDate.Text = permit.PermitDate.ToShortDateString();
                        }
                        else
                        {
                            txtPerDate.Text = permit.PermitDate.ToShortDateString().Insert(permit.PermitDate.ToShortDateString().Length - 1, "0");
                        }
                    }

                    if (permit.Per_EndDate == DateTime.MinValue)
                    {
                        txtEndDate.Text = "";
                    }
                    else
                    {
                        if (permit.Per_EndDate.ToShortDateString().Split('-')[2].Length > 1)
                        {
                            txtEndDate.Text = permit.Per_EndDate.ToShortDateString();
                        }
                        else
                        {
                            txtEndDate.Text = permit.Per_EndDate.ToShortDateString().Insert(permit.Per_EndDate.ToShortDateString().Length - 1, "0");
                        }
                    }

                    txtArea.Text = permit.Per_Area.ToString();
                    txtNum.Text = permit.Per_Number.ToString();
                    txtTel.Text = permit.Per_Tel;
                    txtMark.Text = permit.Per_Mark;
                    txtScope.Text = permit.Per_Scope;

                    bool edit = assAcc.IsEditAssgin(user.USER_ID);
                    bool print = assAcc.IsPrintAssgin(user.USER_ID);

                    btnEdit.Visible = edit;
                    btnPrint.Visible = print;
                    btnDelete.Visible = edit;
                    btnReset.Visible = edit;
                    Session["Per_ID"] = Request.QueryString["per_ID"];

                }

            }


        }



        /// <summary>
        ///修改按钮按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnEdit_Click(object sender, EventArgs e)
        {


            if (!MeetingManagerLib.DataTypeCheck.IsDigit(txtNum.Text))
            {
                Page.RegisterStartupScript("this5", "<script>alert('从业人数必须是数字！')</script>");
                return;
            }
            if (!MeetingManagerLib.DataTypeCheck.IsDigit(txtArea.Text))
            {
                Page.RegisterStartupScript("this6", "<script>alert('经营面积必须是数字！')</script>");
                return;
            }
            if (rblRep.SelectedIndex == -1)
            {
                Page.RegisterStartupScript("this6", "<script>alert('选择法人代表的身份性质！')</script>");
                return;
            }

            if (txtPerCode.Text != "" && hdCode.Value != txtPerCode.Text)
            {

                if (perAcc.GetPermit(txtPerCode.Text).Per_ID > 0)
                {
                    Page.RegisterStartupScript("this20", "<script>alert('该证号已存在！')</script>");
                    return;
                }
            }
            PermitTable permit = new PermitTable();

            permit.Per_Department = txtDepartment.Text;
            permit.Per_Address = txtAddress.Text;
            permit.Per_Type = ddlType.SelectedValue;

            permit.Per_Mark = txtMark.Text;
            permit.Per_Scope = txtScope.Text;
            permit.Per_PermitCode = txtPerCode.Text;
            permit.Per_Organ = ddlOrgan.SelectedItem.Text;
            permit.Per_Representative = txtRep.Text + '（' + rblRep.SelectedValue + '）';
            if (txtPerDate.Text != "")
            {
                permit.PermitDate = Convert.ToDateTime(txtPerDate.Text);

            }
            permit.Per_PerType = rblDatetype.SelectedValue;
            permit.Per_StarDate = permit.PermitDate;

            if (rblDatetype.SelectedIndex != 0)
            {
                permit.Per_EndDate = Convert.ToDateTime(txtEndDate.Text);
            }
            else
            {               
                permit.Per_EndDate = permit.Per_StarDate.AddYears(3).AddDays(-1);
            }
            permit.Per_Tel = txtTel.Text;
            permit.Per_Area = double.Parse(txtArea.Text);
            permit.Per_Number = Convert.ToInt32(txtNum.Text);

            permit.Per_Flag = 0;
            permit.Per_InputDate = DateTime.Now;

            UserTable user = (UserTable)Session["UserTable"];
            permit.Per_InputPersion = user.NAME;

            permit.Per_ID = Convert.ToInt32(Request.QueryString["per_ID"]);

            int count = perAcc.UpdatePermit(permit);
            if (count > 0)
            {
                Response.Redirect("PermitInfo.aspx?Sturt=Edit&per_ID=" + Request.QueryString["per_ID"]);
            }
            else
            {
                Page.RegisterStartupScript("this9", "<script>alert('修改失败！请查看网络是否连接')</script>");
            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int count = perAcc.UpdatePermit(Convert.ToInt32(Request.QueryString["per_ID"]));

            if (count > 0)
            {
                Session["Per_ID"] = null;
                Response.Redirect("queryPermit.aspx?Sturt=Edit");
            }
            else
            {
                Page.RegisterStartupScript("this10", "<script>alert('删除数据失败！请查看网络是否连接！')</script>");
            }
            
        }

        /// <summary>
        /// 重置按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnReset_Click(object sender, EventArgs e)
        {

            txtDepartment.Text = "";
            txtRep.Text = "";
            txtAddress.Text = "";
            ddlType.SelectedIndex = 0;
            ddlOrgan.SelectedIndex = 0;
            txtPerDate.Text = "";
            txtEndDate.Text = "";
            txtTel.Text = "";
            txtArea.Text = "0.0";
            txtNum.Text = "0";
            rblRep.SelectedIndex = -1;
            txtMark.Text = "";

        }

        protected void btnPrint_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/print/PrintParameter.aspx");
        }

        protected void btnAutoCode_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(DateTime.Now.Year.ToString());
            PermitTable permit = perAcc.GetPermit(Convert.ToInt32(Request.QueryString["per_ID"]));
            sb.Append(permit.Per_AreaCode.ToString());
            int count = perAcc.GetPermitCount(permit.Per_AreaCode, DateTime.Now.Year);
            bool flag;
            do
            {
                string temp = sb.ToString();
                flag = false;
                count++;
                for (int index = 0; index < (6 - count.ToString().Length); index++) //根据个数生成后六位数字
                {
                    sb.Append(0);
                }
                sb.Append(count);
                if (perAcc.GetPermit(sb.ToString()).Per_ID > 0) //判断是否存在
                {
                    sb.Remove(0, sb.Length);
                    sb.Append(temp);
                    flag = true;

                }
                else
                {
                    txtPerCode.Text = "";
                    txtPerCode.Text = sb.ToString();
                    btnAutoCode.Enabled = false;
                }
            } while (flag);

        }

        protected void rblDatetype_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblDatetype.SelectedIndex != 0)
            {            
                lblEndDate.Enabled = true;
                txtEndDate.Enabled = true;
            }
            else
            {

                lblEndDate.Enabled = false;
                txtEndDate.Enabled = false;
            }
        }

    }
}
